<template>
    <div class="news">
        <newtitle></newtitle>
        <newlist>
            <newitem v-for="friend in friendlist" :call='friend.callcode' :key="friend.id">
                <template v-slot:headimg>
                    <img :src="friend.headimg"
                    style="margin: 5px auto; border-radius: 50%; width: 40px; height: 40px" />
                </template>
                <template v-slot:username>
                    <span>{{friend.name}}</span>
                </template>
            </newitem>
        </newlist>
    </div>
</template>

<script>
import axios from 'axios';
import { computed } from 'vue';
import { useStore } from 'vuex';
import Newtitle from '../components/newsview/Newtitle.vue';
import Newlist from '../components/newsview/Newlist.vue';
import Newitem from '../components/newsview/Newitem.vue';

export default {
  name: 'News',
  components: {
    Newtitle,
    Newlist,
    Newitem,
  },
  setup() {
    const Store = useStore();

    // 第一次加载好友页面，从服务器获取好友列表，存放在vuex
    if (Store.state.friendlist.friendslist.length === 0) {
      // 获取token值
      const token = JSON.parse(window.sessionStorage.getItem('token'));
      // 获取好友list
      axios({
        method: 'post',
        url: 'http://1.14.122.88:5001/my/friendlist',
        headers: {
          authorization: token,
        },
      }).then(
        (response) => {
          if (response.data.status === 2) {
            // 储存好友信息到vuex
            Store.commit('ADDFRIENDLIST', response.data.friendlist);
          }
        },
        (error) => {
          console.log('获取好友名单失败', error.message);
        },
      );
    }

    const friendlist = computed(() => Store.state.friendlist.friendslist);

    return {
      friendlist,
    };
  },
};
</script>

<style scoped>
</style>
